package web

import (
	"net/http"
	"path/filepath"

	"github.com/ev-charging/cloud-platform/config"
	"github.com/ev-charging/cloud-platform/internal/api"
	"github.com/ev-charging/cloud-platform/internal/api/handlers"
	"github.com/gin-gonic/gin"
)

// Server Web服务器
type Server struct {
	router         *gin.Engine
	config         *config.ServerConfig
	deviceHandler  *handlers.DeviceHandler
	pricingHandler *handlers.PricingHandler
}

// NewServer 创建Web服务器实例
func NewServer(cfg *config.ServerConfig, deviceHandler *handlers.DeviceHandler, pricingHandler *handlers.PricingHandler) *Server {
	// 创建Gin路由器
	router := gin.Default()

	// 设置模板目录
	templatePath := filepath.Join("web", "templates")
	router.LoadHTMLGlob(filepath.Join(templatePath, "*.html"))

	// 设置静态文件目录
	staticPath := filepath.Join("web", "static")
	router.Static("/static", staticPath)

	// 设置API路由
	api.SetupRoutes(router, deviceHandler, pricingHandler)

	// 设置Web页面路由
	setupWebRoutes(router)

	return &Server{
		router:         router,
		config:         cfg,
		deviceHandler:  deviceHandler,
		pricingHandler: pricingHandler,
	}
}

// setupWebRoutes 设置Web页面路由
func setupWebRoutes(router *gin.Engine) {
	// 首页
	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "新能源充电桩云平台",
		})
	})

	// 设备管理页面
	router.GET("/devices", func(c *gin.Context) {
		c.HTML(http.StatusOK, "devices.html", gin.H{
			"title": "设备管理 - 新能源充电桩云平台",
		})
	})

	// 交易记录页面
	router.GET("/transactions", func(c *gin.Context) {
		c.HTML(http.StatusOK, "transactions.html", gin.H{
			"title": "交易记录 - 新能源充电桩云平台",
		})
	})

	// 电价策略页面
	router.GET("/pricing", func(c *gin.Context) {
		c.HTML(http.StatusOK, "pricing.html", gin.H{
			"title": "电价策略 - 新能源充电桩云平台",
		})
	})

	// 数据分析页面
	router.GET("/reports", func(c *gin.Context) {
		c.HTML(http.StatusOK, "reports.html", gin.H{
			"title": "数据分析 - 新能源充电桩云平台",
		})
	})
}

// Run 启动Web服务器
func (s *Server) Run() error {
	addr := ":" + s.config.Port
	return s.router.Run(addr)
}
